/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.console.command;

import org.openislands.oi.console.config.OIConsole;
import org.openislands.oi.console.config.annotation.Command;
import org.openislands.oi.console.config.annotation.CommandArgs;
import org.openislands.oi.console.config.annotation.SingleCommandGroup;
import org.openislands.oi.util.CommandUtils;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("unused")
@SingleCommandGroup("native")
public class NativeCommand {

    @Command(value = "cmd", desc = "execute external env command")
    public String cmd(/*@CommandParam(desc = "execute cmd max timeout(seconds)", defaultValue = "10", required = false) Integer timeout,*/
            @CommandArgs String[] args) throws InterruptedException {
        int timeout = 10;

        long startTime = System.nanoTime();
        // String[] commands = ParameterUtils.filterParams(args, "--timeout");
        String[] commands = args;
        commands = CommandUtils.isUnix() ? new String[]{"/bin/sh", "-c", String.join(" ", commands)} : commands;
        String subprocess = CommandUtils.startSyncSubprocess(commands, new HashMap<>(), null,
                new CommandUtils.OnCommandExecOutputCallback() {
                    @Override
                    public void onSubprocessSuccess(String line) {
                        OIConsole.console(line);
                    }

                    @Override
                    public void onSubprocessError(String line) {
                        OIConsole.console(line);
                    }
                }, timeout, TimeUnit.SECONDS);

        if (TimeUnit.SECONDS.toNanos(timeout) - (System.nanoTime() - startTime) < 0) {
            Thread.sleep(100);
            return "---interrupted waiting for " + timeout + "s---";
        }

        return "------";
    }
}
